package com.hotdog.config;

import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.Arrays;

/**
 * @author dell
 */
@AllArgsConstructor
@Configuration
@EnableAuthorizationServer //启用授权服务器
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {
    /**
     * 此对象负责认证管理
     */
    private AuthenticationManager authenticationManager;
    /**
     * TokenStore负责完成令牌的创建 信息的读取
     */
    private TokenStore tokenStore;
    /**
     * 负责获取用户的详情信息 username password client ***
     */
    private ClientDetailsService clientDetailsService;
    /**
     * JWT令牌转换器(基于用户构建令牌,解析令牌)
     */
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    /**
     * 密码加密匹配器
     */
    private PasswordEncoder passwordEncoder;
    /**负责获取用户详细信息*/
    private UserDetailsService userDetailsService;

    /**
     * 设置认证端点的配置
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints//端点
                //配置认证管理器
                .authenticationManager(authenticationManager)
                //验证用户的方法获得用户详情
                /**
                 * 封装用户登录时 信息的获取与封装
                 * 在页面上点击登录按钮时 会调用这个对象的  loadUserByUsername方法
                 * UserDetails封装用户信息*/
                /*对用户的信息进行校验*/
                .userDetailsService(userDetailsService)
                //要求提交认证使用post请求方式,提高安全性
                .allowedTokenEndpointRequestMethods(HttpMethod.POST, HttpMethod.GET)
                //要配置令牌的生成,由于令牌生成比较复杂,下面有方法实现
                .tokenServices(tokenService());
    }

    /**
     * 定义令牌生成策略
     *
     * @return
     */
    @Bean
    public AuthorizationServerTokenServices tokenService() {
        //这个方法的目标就是获得一个令牌生成器
        DefaultTokenServices services = new DefaultTokenServices();
        //支持令牌刷新策略
        services.setSupportRefreshToken(true);
        //设置令牌生成策略(tokenStroe 在TokenConfig中配置)
        services.setTokenStore(tokenStore);
        //设置令牌增强(固定用法 令牌Payload中允许添加扩展数据)
        TokenEnhancerChain chain = new TokenEnhancerChain();
        chain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter));
        //令牌增强对象设置到令牌生成
        services.setTokenEnhancer(chain);
        //设置令牌有效期
        services.setAccessTokenValiditySeconds(3600);
        //刷新令牌应用场景：一般在用户登录系统后，令牌快过期时，系统自动帮助用户刷新令牌，提高用户的体验感
        services.setRefreshTokenValiditySeconds(3600 * 72);
        //配置客户端详情
        services.setClientDetailsService(clientDetailsService);
        return services;
    }

    /**
     * 设置客户端详情类似于用户详情
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //客户端id
                .withClient("gateway-client")
                //客户端秘钥
                .secret(passwordEncoder.encode("123456"))
                //设置权限
                .scopes("all")
                //允许客户端进行的操作  里面的字符串千万不能写错
                .authorizedGrantTypes("password", "refresh_token");
    }

    /**
     * 认证成功后的安全约束配置
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //认证通过后,允许客户端进行哪些操作
        security
                //公开oauth/token_key端点
                .tokenKeyAccess("permitAll()")
                //公开oauth/check_token端点
                .checkTokenAccess("permitAll()")
                //允许提交请求进行认证(申请令牌)
                .allowFormAuthenticationForClients();
    }
}

